<template>
  <div class="app-container">
    <el-container>
      <el-header>
        <el-row type="flex" justify="space-between" align-items="center">
          <el-button type="success" icon="el-icon-plus" @click="handleAdd">添加投标项目</el-button>
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            class="search-form"
          >
            <el-form-item>
              <el-input
                v-model="searchTerm"
                placeholder="搜索项目名称/机会号"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-row>
      </el-header>
    </el-container>
    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column label="机会合同号" align="center" prop="projectNo" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="项目状态" align="center" prop="status" />
      <el-table-column label="负责人" align="center" prop="projectManager" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <div class="operation-links">
            <a href="javascript:void(0)" class="operation-link" @click="handleUpdate(scope.row)"
               v-hasPermi="['system:project:edit']">查看</a>
            <a href="javascript:void(0)" class="operation-linkred" @click="handleArchive(scope.row)"
               v-hasPermi="['system:project:remove']">存档</a>
            <router-link
              :to="'/pm/project/report/' + scope.row.id"
              class="operation-link"
              v-hasPermi="['system:project:edit']">
              查看报表
            </router-link>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加项目基本信息对话框 -->
    <el-dialog :title="title" :visible.sync="addOpen" width="500px" append-to-body>
      <el-form ref="addForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="机会合同号" prop="projectNo">
          <el-input v-model="form.projectNo" placeholder="请输入机会合同号" />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目状态" prop="description">
          <el-input v-model="form.status" type="textarea" placeholder="请输入状态" />
        </el-form-item>
        <el-form-item label="项目负责人" prop="projectManager">
          <el-input v-model="form.projectManager" placeholder="请输入项目负责人" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createUserId">
          <el-input v-model="form.createTime" placeholder="请输入创建时间" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addSubmitForm">确 定</el-button>
        <el-button @click="addCancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改项目基本信息对话框 -->
    <el-dialog :title="title" :visible.sync="updateOpen" width="500px" append-to-body>
      <el-form ref="updateForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="机会合同号" prop="projectNo">
          <el-input v-model="form.projectNo" placeholder="请输入机会合同号" />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目状态" prop="description">
          <el-input v-model="form.status" type="textarea" placeholder="请输入状态" />
        </el-form-item>
        <el-form-item label="项目负责人" prop="projectManager">
          <el-input v-model="form.projectManager" placeholder="请输入项目负责人" />
        </el-form-item>
        <el-form-item label="存档状态" prop="archiveStatus">
          <el-input v-model="form.archiveStatus" placeholder="请更改存档状态" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createUserId">
          <el-input v-model="form.createTime" placeholder="请输入创建时间" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateSubmitForm">确 定</el-button>
        <el-button @click="updateCancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 存档确认对话框 -->
    <el-dialog
      title="存档"
      :visible.sync="archiveOpen"
      width="400px"
      append-to-body>
      <el-form ref="archiveForm" :model="archiveForm" label-width="80px">
        <el-form-item label="原因" prop="archiveReason">
          <el-select v-model="archiveForm.archiveReason" placeholder="请选择">
            <el-option
              v-for="item in reasonOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item v-if="archiveForm.archiveReason==='其他'" label="说明">
          <el-input
            v-model="archiveForm.archiveReasonText"
            type="textarea"
            :rows="3"
            placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="archiveCancel">关 闭</el-button>
        <el-button type="primary" :loading="archiveLoading" @click="confirmArchive">确 定</el-button>
      </div>
    </el-dialog>
    </div>
</template>

<script>
import { listProject, addProject, updateProject,archive } from "@/api/pm/bid"
export default {
  name: "bid",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      archiveLoading: false,   // 存档按钮加载锁
      //存档弹窗
      archiveOpen: false,
      archiveForm: {
        id: null,
        archiveReason: '',
        archiveReasonText: '',  // 仅当“其他”时使用
        archiveTime : null,
        archiveStatus: 0,

      },
        // 下拉原因选项
        reasonOptions: [
          { label: '公司业务', value: '公司业务' },
          { label: '客户回溯', value: '客户回溯' },
          { label: '留存档案', value: '留存档案' },
          { label: '其他', value: '其他' }
        ],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目基本信息表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      addOpen: false,
      updateOpen: false,
      searchTerm: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectNo: undefined,
        projectName: undefined,
        status: null,
        projectManager: null,
        createTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        projectNo: [
          { required: true, message: "项目编号不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "项目状态：未开始, 已完结不能为空", trigger: "change" }
        ],
        projectManager: [
          { required: true, message: "负责人不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        archiveStatus: [
          { required: true, message: "存档状态：0-未存档，1-已存档不能为空", trigger: "change" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 打开存档弹窗 */
    handleArchive(row) {
      if (!row || !row.id) {
        this.$message.warning('未获取到当前行数据，请刷新页面再试');
        return;
      }

      // ✅ 新增：已存档判断
      if (row.archiveStatus === 1) {
        this.$message.info('📦 该项目已存档，无需重复存档');
        return;
      }

      this.archiveForm = {
        id: row.id,
        archiveReason: row.archiveReason || '',
        archiveStatus: row.archiveStatus ?? 0,
        archiveTime: row.archiveTime || null,
        archiveReasonText: ''
      };
      this.archiveOpen = true;
    },
    confirmArchive() {
      if (this.archiveLoading) return;          // 已经点过一次，直接返回
      this.archiveLoading = true;               // 加锁

      const reason = this.archiveForm.archiveReason === '其他'
        ? this.archiveForm.archiveReasonText
        : this.archiveForm.archiveReason;

      if (!reason || reason.trim() === '') {
        this.$message.warning('请选择或填写存档原因');
        this.archiveLoading = false;            // 校验不过也要解锁
        return;
      }

      const params = {
        id: this.archiveForm.id,
        archiveReason: reason.trim(),
        archiveStatus: this.archiveForm.archiveStatus || 1,
        archiveTime: new Date().toLocaleString('zh-CN', { hour12: false }).replace(/\//g, '-')
      };

      archive(params)
        .then(res => {
          const idx = this.projectList.findIndex(p => p.id === this.archiveForm.id);
          if (idx > -1) this.$set(this.projectList, idx, res.data);
          this.$message.success('📁 项目存档成功');
          this.archiveOpen = false;
          this.$refs.archiveForm?.resetFields();
        })
        .catch(err => {
          // 把后端返回的“重复提交”提示直接甩给用户
          this.$message.error(err.msg || '存档失败，请稍后再试');
        })
        .finally(() => {
          this.archiveLoading = false;   // 无论成功失败都解锁
        });
    },
    /** 关闭存档弹窗 */
    archiveCancel() {
      this.archiveOpen = false
      this.$refs.archiveForm?.resetFields()
    },
    /** 查询项目基本信息列表 */
    getList() {
      this.loading = true
      listProject(this.queryParams).then(res => {
        this.projectList = res.rows
        this.total = res.total
        this.loading = false
      })
    },
    // 添加取消按钮
  addCancel() {
    this.$refs.addForm.resetFields();  // 【改动】重置新增表单
    this.addOpen = false;
    },
    //修改取消按钮
    updateCancel() {
      this.$refs.updateForm.resetFields(); // 【改动】重置修改表单
      this.updateOpen = false;
    },
    // 表单重置
    reset() {
      this.form = {
        projectNo: null,
        projectName: null,
        status: null,
        projectManager: null,
        createTime: null,
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      console.log('前端传递的参数:', this.queryParams);

      // 清空旧字段，避免干扰
      this.queryParams.projectName = undefined;
      this.queryParams.projectNo = undefined;

      // 判断用户输入的是编号还是名称（简单规则）
      const term = this.searchTerm?.trim();
      if (!term) {
        this.getList();
        return;
      }

      // 简单判断：如果是数字或字母+数字组合，优先当作编号
      if (/^[a-zA-Z0-9-_]+$/.test(term)) {
        this.queryParams.projectNo = term;
      } else {
        this.queryParams.projectName = term;
      }

      this.queryParams.pageNum = 1; // 搜索时重置分页
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 清空搜索框
      this.searchTerm = '';

      // 恢复查询参数为初始状态
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        projectNo: undefined,
        projectName: undefined,
        status: null,
        projectManager: null,
        createTime: null,
      };

      // 重新加载列表
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.from = {}
      this.addOpen = true
      this.title = "添加项目基本信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = { ...row }; // 直接深拷贝 row
      this.updateOpen = true;
      this.title = "修改项目基本信息";
    },
    /** 提交按钮 */
   updateSubmitForm() {
      this.$refs["updateForm"].validate(valid => {
        if (valid) {
          updateProject(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.updateOpen = false;
            this.getList(); // 刷新列表
          });
        }
      });
    },
    /** 提交按钮 */
    addSubmitForm() {
      this.$refs.addForm.validate(valid => {
        if (!valid) return;
        addProject(this.form).then(() => {
          this.$modal.msgSuccess('新增成功');
          this.addOpen = false;      // 【改动】关新增弹窗
          this.getList();
        });
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/project/export', {
        ...this.queryParams
      }, `project_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style scoped>
.search-form {
  display: flex;
  align-items: center;
}

.operation-links {
  display: flex;
  justify-content: flex-start; /* 水平起始对齐 */
  align-items: center;
}

.operation-link {
  margin-right: 16px; /* 设置右侧间距 */
  color: #409EFF; /* Element UI 的主题色 */
  cursor: pointer;
  font-size: 14px;
  text-decoration: none; /* 去掉下划线 */
}

.operation-link:hover {
  text-decoration: underline;
}

.operation-link:last-child {
  margin-right: 0; /* 最后一个元素不设置右侧间距 */
}


.operation-linkred {
  margin-right: 16px;/* 设置左右间距 */
  color: red;
  font-size: 14px;
  cursor: pointer;
  text-decoration: none; /* 去掉下划线 */
}



</style>
